# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: jingyuan


from ..on_log import OnLog
from .base import OrderInfoTracker, ExportDataFrame


class OrderLifetime(OrderInfoTracker, ExportDataFrame, OnLog):
  """
  checks the maximum order lifetime
  """
  def __init__(self, lifetime_limit):
    """
    Args:
      lifetime_limit: the maximum order lifetime limit in seconds
    """
    super().__init__()
    self.lifetime_limit = lifetime_limit * 1e9
    self.ts_fields += ['fill_ts']

  def on_fill(self, ts, currency, order_id, order_side, fill_price, fill_qty, maker):
    if order_id in self.order_info:
      submit_ts = self.order_info[order_id]['submit_ts']
      if ts - submit_ts > self.lifetime_limit:
        self.errors[order_id] = {
            'fill_ts': ts,
            'lifetime(sec)': (ts - submit_ts) / 1e9,
            'order_id': order_id,
        }
        self.errors[order_id].update(self.order_info[order_id])

  def to_df(self):
    return super().to_df().sort_values('lifetime(sec)', ascending=False)
